import { useUserStore } from '@/store/modules/user';
import { computed } from 'vue';

export function usePermission() {
	const userStore = useUserStore();
	const permissionList = computed(() => userStore.getPermissions);

	/**
	 * 检查是否是数组
	 */
	const checkArray = (accesses, error) => {
		if (!Array.isArray(accesses)) {
			throw new Error(`[${error}]: ${accesses} 应该是一个数组！`);
		}
	};

	/**
	 * 检查权限
	 * @param Array accesses
	 */
	const _somePermissions = (accesses) => {
		checkArray(accesses, '_somePermissions');
		return permissionList.value.some((item) => accesses.includes(item));
	};

	/**
	 * 判断是否存在权限
	 * 可用于 v-if 显示逻辑
	 * */
	const hasPermission = (accesses) => {
		if (!accesses || !accesses.length) return true;
		return _somePermissions(accesses);
	};

	/**
	 * 是否包含指定的所有权限
	 * @param Array accesses
	 */
	const hasEveryPermission = (accesses) => {
		checkArray(accesses, 'hasEveryPermission');
		return permissionList.value.every((access) => accesses.includes(access.value));
	};

	/**
	 * 是否包含其中某个权限
	 * @param accesses
	 * @param accessMap
	 */
	const hasSomePermission = (accesses) => {
		checkArray(accesses, 'hasSomePermission');
		return permissionList.value.some((access) => accesses.includes(access.value));
	};

	return { hasPermission, hasEveryPermission, hasSomePermission };
}
